<template>
  <ArtTableFullScreen>
    <div class="menu-page" id="table-full-screen" :style="{ height: containerMinHeight}">
      <!-- 搜索栏 -->
      <ArtSearchBar
        v-model:filter="formFilters"
        :items="formItems"
        :showExpand="false"
        @reset="handleReset"
        @search="handleSearch"
      ></ArtSearchBar>

      <ElCard shadow="never" class="art-table-card" style="height: calc(100vh - 214px);">
        <!-- 表格头部 -->
        <ArtTableHeader :showZebra="false" v-model:columns="columnChecks" @refresh="handleRefresh">
          <template #left>
            <!-- 按钮权限：后端控制模式，使用自定义指令 -->
            <ElButton @click="openDialog('add','folder','-1', null, true)" v-ripple>
              添加
            </ElButton>
            <ElButton @click="toggleExpand" v-ripple>
              {{ isExpanded ? '收起' : '展开' }}
            </ElButton>
            <!-- 按钮权限：前端控制模式，使用 hasAuth 方法 -->
            <!-- <ElButton v-if="hasAuth('B_CODE1')" @click="showModel('menu', null, true)" v-ripple>
              添加菜单
            </ElButton> -->
          </template>
        </ArtTableHeader>
		<div style="height: calc(100% - 35px);">
			<!-- 表格 -->
			<ArtTable
			  rowKey="id"
			  ref="tableRef"
			  :loading="loading"
			  :data="tableData"
			  :marginTop="10"
			  :stripe="false"
			  :height="'100%'"
			>
			  <template #default>
				<ElTableColumn v-for="col in columns" :key="col.prop || col.type" v-bind="col" />
			  </template>
			</ArtTable>
		</div>
        <ElDialog :title="dialogTitle" v-model="dialogVisible" width="700px" align-center>
          <ElForm ref="formRef" :model="form" :rules="rules" label-width="85px">
            <ElFormItem label="类型">
              <ElRadioGroup v-model="labelPosition" :disabled="disableMenuType">
			    <ElRadioButton value="folder" label="folder">目录</ElRadioButton>
				<ElRadioButton value="menu" label="menu">菜单</ElRadioButton>
                <ElRadioButton value="btn" label="btn">权限</ElRadioButton>
              </ElRadioGroup>
            </ElFormItem>
			
			<template v-if="labelPosition === 'folder'">
			  <ElRow :gutter="20">
			    <ElCol :span="12">
			      <ElFormItem label="中文" prop="cnName">
			        <ElInput v-model="form.cnName" placeholder="中文名称"></ElInput>
			      </ElFormItem>
			    </ElCol>
				<ElCol :span="12">
				  <ElFormItem label="英文" prop="enName">
				    <ElInput v-model="form.enName" placeholder="英文名称"></ElInput>
				  </ElFormItem>
				</ElCol>
			  </ElRow>
			  
			  <ElRow :gutter="20">
				<ElCol :span="12">
				  <ElFormItem label="标识" prop="code">
					<ElInput v-model="form.code" placeholder="标识"></ElInput>
				  </ElFormItem>
				</ElCol>
				<ElCol :span="12">
				  <ElFormItem label="路由" prop="path">
					<ElInput v-model="form.path" placeholder="路由"></ElInput>
				  </ElFormItem>
				</ElCol>
			  </ElRow>
			  
			  <ElRow :gutter="20">
			    <ElCol :span="24">
			      <ElFormItem label="组件" prop="component">
			        <ElInput v-model="form.component" placeholder="组件"></ElInput>
			      </ElFormItem>
			    </ElCol>
			  </ElRow>
			
			  <ElRow :gutter="20">
				<ElCol :span="12">
				  <ElFormItem label="图标" prop="icon">
				    <ArtIconSelector v-model="form.icon" :iconType="iconType" width="100%" />
				  </ElFormItem>
				</ElCol>  
			    <ElCol :span="12">
			      <ElFormItem label="排序" prop="sort" style="width: 100%">
			        <ElInputNumber
			          v-model="form.sort"
			          style="width: 100%"
			          @change="handleChange"
			          :min="1"
			          controls-position="right"
			        />
			      </ElFormItem>
			    </ElCol>
			  </ElRow>
			  
			  <ElRow :gutter="20">
			    <ElCol :span="5">
			      <ElFormItem label="是否启用" prop="enabled">
			        <ElSwitch v-model="form.enabled" active-value="0" inactive-value="1"></ElSwitch>
			      </ElFormItem>
			    </ElCol>
			    <ElCol :span="5">
			      <ElFormItem label="是否显示" prop="show">
			        <ElSwitch v-model="form.show" active-value="0" inactive-value="1"></ElSwitch>
			      </ElFormItem>
			    </ElCol>
			  </ElRow>
			</template>

            <template v-if="labelPosition === 'menu'">
			  <ElRow :gutter="20">
			    <ElCol :span="12">
			      <ElFormItem label="中文名称" prop="cnName">
			        <ElInput v-model="form.cnName" placeholder="中文名称"></ElInput>
			      </ElFormItem>
			    </ElCol>
				<ElCol :span="12">
				  <ElFormItem label="英文名称" prop="enName">
				    <ElInput v-model="form.enName" placeholder="英文名称"></ElInput>
				  </ElFormItem>
				</ElCol>
			  </ElRow>

			  <ElRow :gutter="20">
				<ElCol :span="12">
				  <ElFormItem label="标识" prop="code">
					<ElInput v-model="form.code" placeholder="标识"></ElInput>
				  </ElFormItem>
				</ElCol>
				<ElCol :span="12">
				  <ElFormItem label="路由" prop="path">
					<ElInput v-model="form.path" placeholder="路由"></ElInput>
				  </ElFormItem>
				</ElCol>
			  </ElRow>
			  
			  <ElRow :gutter="20">
			    <ElCol :span="24">
			      <ElFormItem label="组件" prop="component">
			        <ElInput v-model="form.component" placeholder="组件"></ElInput>
			      </ElFormItem>
			    </ElCol>
			  </ElRow>			  
			  
			  <ElRow :gutter="20">
				<ElCol :span="12">
				  <ElFormItem label="图标" prop="icon">
				    <ArtIconSelector v-model="form.icon" :iconType="iconType" width="100%" />
				  </ElFormItem>
				</ElCol>  
			    <ElCol :span="12">
			      <ElFormItem label="排序" prop="sort" style="width: 100%">
			        <ElInputNumber
			          v-model="form.sort"
			          style="width: 100%"
			          @change="handleChange"
			          :min="1"
			          controls-position="right"
			        />
			      </ElFormItem>
			    </ElCol>
			  </ElRow>
			  
			  <ElRow :gutter="20" v-if="form.isIframe=='0'">
			    <ElCol :span="24">
			      <ElFormItem label="链接" prop="link">
			        <ElInput v-model="form.link" placeholder="外部链接/内嵌地址(https://www.baidu.com)"></ElInput>
			      </ElFormItem>
			    </ElCol>
			  </ElRow>	

              <ElRow :gutter="20">
                <ElCol :span="5">
                  <ElFormItem label="是否启用" prop="enabled">
                    <ElSwitch v-model="form.enabled" active-value="0" inactive-value="1"></ElSwitch>
                  </ElFormItem>
                </ElCol>
                <ElCol :span="5">
                  <ElFormItem label="页面缓存" prop="keepAlive">
                    <ElSwitch v-model="form.keepAlive" active-value="0" inactive-value="1"></ElSwitch>
                  </ElFormItem>
                </ElCol>
                <ElCol :span="5">
                  <ElFormItem label="是否显示" prop="show">
                    <ElSwitch v-model="form.show" active-value="0" inactive-value="1"></ElSwitch>
                  </ElFormItem>
                </ElCol>
                <ElCol :span="5">
                  <ElFormItem label="是否内嵌" prop="isIframe" >
                    <ElSwitch v-model="form.isIframe" active-value="0" inactive-value="1"></ElSwitch>
                  </ElFormItem>
                </ElCol>
				<ElCol :span="5">
				  <ElFormItem label="固定Tab" prop="fixed" >
				    <ElSwitch v-model="form.fixed" active-value="0" inactive-value="1"></ElSwitch>
				  </ElFormItem>
				</ElCol>
              </ElRow>
            </template>

            <template v-if="labelPosition === 'btn'">
			  <ElRow :gutter="20">
			    <ElCol :span="12">
			      <ElFormItem label="中文" prop="cnName">
			        <ElInput v-model="form.cnName" placeholder="中文名称"></ElInput>
			      </ElFormItem>
			    </ElCol>
				<ElCol :span="12">
				  <ElFormItem label="英文" prop="enName">
				    <ElInput v-model="form.enName" placeholder="英文名称"></ElInput>
				  </ElFormItem>
				</ElCol>
			  </ElRow>

			  <ElRow :gutter="20">
			    <ElCol :span="12">
			      <ElFormItem label="标识" prop="code">
			        <ElInput v-model="form.code" placeholder="权限标识"></ElInput>
			      </ElFormItem>
			    </ElCol> 
			    <ElCol :span="12">
			      <ElFormItem label="排序" prop="sort" style="width: 100%">
			        <ElInputNumber
			          v-model="form.sort"
			          style="width: 100%"
			          @change="handleChange"
			          :min="1"
			          controls-position="right"
			        />
			      </ElFormItem>
			    </ElCol>
			  </ElRow>
            </template>
          </ElForm>

          <template #footer>
            <span class="dialog-footer">
              <ElButton @click="dialogVisible = false">取 消</ElButton>
              <ElButton type="primary" @click="submitForm()">确 定</ElButton>
            </span>
          </template>
        </ElDialog>
      </ElCard>
    </div>
  </ArtTableFullScreen>
</template>

<script setup lang="ts">
  import { useMenuStore } from '@/store/modules/menu'
  import type { FormInstance, FormRules } from 'element-plus'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { IconTypeEnum } from '@/enums/appEnum'
  import ArtButtonTable from '@/components/core/forms/ArtButtonTable.vue'
  import { useCheckedColumns } from '@/composables/useCheckedColumns'
  import { ElPopover, ElButton } from 'element-plus'
  import dayjs from 'dayjs';
  import { AppRouteRecord } from '@/types/router'
  import { useAuth } from '@/composables/useAuth'
  import { SearchFormItem } from '@/types'
  import { MenuService } from '@/api/menuApi'
  import { useI18n } from 'vue-i18n'
  import { useCommon } from '@/composables/useCommon'
  const { containerMinHeight } = useCommon()
  const { locale } = useI18n()
  defineOptions({ name: 'Menu' })

  const { hasAuth } = useAuth()

  const { menuList } = storeToRefs(useMenuStore())

  const loading = ref(false)

  // 定义表单搜索初始值
  const initialSearchState = {
    cnName: '',
	enName: ''
  }

  // 响应式表单数据
  const formFilters = reactive({ ...initialSearchState })

  // 增加实际应用的搜索条件状态
  const appliedFilters = reactive({ ...initialSearchState })

  // 重置表单
  const handleReset = () => {
    Object.assign(formFilters, { ...initialSearchState })
    Object.assign(appliedFilters, { ...initialSearchState })
    getTableData()
  }

  // 搜索处理
  const handleSearch = () => {
    // 将当前输入的筛选条件应用到实际搜索
    Object.assign(appliedFilters, { ...formFilters })
    getTableData()
  }

  // 表单配置项
  const formItems: SearchFormItem[] = [
    {
      label: '中文名称',
      prop: 'cnName',
      type: 'input',
      config: {
        clearable: true
      }
    },
    {
      label: '英文名称',
      prop: 'enName',
      type: 'input',
      config: {
        clearable: true
      }
    }
  ]

  // 构建菜单类型标签
  const buildMenuTypeTag = (row: any) => {
	  
    if (row.type=='folder') {
      return 'info'
    } else if (row.type=='menu') {
      return 'success'
    } else if (row.type=='btn') {
      return 'primary'
    } else if (row.meta?.link) {
      return 'warning'
    }
  }

  // 构建菜单类型文本
  const buildMenuTypeText = (row: any) => {
	  
	  if (row.type=='folder') {
	    return '目录'
	  } else if (row.type=='menu') {
	    return '菜单'
	  } else if (row.type=='btn') {
	    return '按钮'
	  } else{
	    return 'warning'
	  }
	  
    // if (row.children && row.children.length > 0) {
    //   return '目录'
    // } else if (row.meta?.link && row.meta?.isIframe) {
    //   return '内嵌'
    // } else if (row.path) {
    //   return '菜单'
    // } else if (row.meta?.link) {
    //   return '外链'
    // }
  }

  // 动态列配置
  const { columnChecks, columns } = useCheckedColumns(() => [
    {
      prop: 'cnName',
      label: '中文名称',
      minWidth: 120
    },
	{
	  prop: 'enName',
	  label: '英文名称',
	  minWidth: 120
	},
    {
      prop: 'type',
      label: '类型',
      formatter: (row: any) => {
        return h(ElTag, { type: buildMenuTypeTag(row) }, () => buildMenuTypeText(row))
      }
    },
    {
      prop: 'path',
      label: '路由',
      formatter: (row: AppRouteRecord) => {
        return row.meta?.link || row.path || ''
      }
    },
	{
	  prop: 'sort',
	  label: '序号'
	},
    // {
    //   prop: 'meta.authList',
    //   label: '可操作权限',
    //   formatter: (row: AppRouteRecord) => {
    //     return h(
    //       'div',
    //       {},
    //       row.meta.authList?.map((item: { title: string; auth_mark: string }, index: number) => {
    //         return h(
    //           ElPopover,
    //           {
    //             placement: 'top-start',
    //             title: '操作',
    //             width: 200,
    //             trigger: 'click',
    //             key: index
    //           },
    //           {
    //             default: () =>
    //               h('div', { style: 'margin: 0; text-align: right' }, [
    //                 h(
    //                   ElButton,
    //                   {
    //                     size: 'small',
    //                     type: 'primary',
    //                     onClick: () => showModel('button', item)
    //                   },
    //                   { default: () => '编辑' }
    //                 ),
    //                 h(
    //                   ElButton,
    //                   {
    //                     size: 'small',
    //                     type: 'danger',
    //                     onClick: () => deleteAuth()
    //                   },
    //                   { default: () => '删除' }
    //                 )
    //               ]),
    //             reference: () => h(ElButton, { class: 'small-btn' }, { default: () => item.title })
    //           }
    //         )
    //       })
    //     )
    //   }
    // },
    {
      prop: 'modifyTime',
      label: '编辑时间',
      formatter: (row:any) => {
		  return dayjs(row.modifyTime).format('YYYY-MM-DD HH:MM:ss')
	  }
    },
    {
      prop: 'status',
      label: '可视性',
      formatter: (row) => {
        return h(ElTag, { type: row.show=='1' ? 'danger' : 'success' }, () =>
          row.show=='1' ? '隐藏' : '显示'
        )
      }
    },
    {
      prop: 'operation',
      label: '操作',
      width: 180,
      formatter: (row: any) => {
        return h('div', [
            (row.type=='folder' || row.type=='menu') && h(ArtButtonTable, {
              type: 'add',
              onClick: () => {
				  if(row.type=='folder'){
					  openDialog('add','menu',row.id,null, true)
				  }
				  else if(row.type=='menu'){
					   openDialog('add','btn',row.id,null, true)
				  }
			  }
            }),
            h(ArtButtonTable, {
              type: 'edit',
              onClick: () => openDialog('edit',row.type,row.parentId,row, true)
            }),
            h(ArtButtonTable, {
              type: 'delete',
              onClick: () => deleteMenu()
            })
        ])
      }
    }
  ])

  const handleRefresh = () => {
    getTableData()
  }

  const dialogVisible = ref(false)
  const form = reactive({
	id:'',
	parentId:'',
	cnName: '',
	enName: '',
	code:'',
	type:'',
	component:'',
	path: '',
	icon: '',
	enabled: 0,
	sort: 1,
	keepAlive: 0,
	show: 0,
	link: '',
	isIframe: 1,
	fixed:1
  })
  const iconType = ref(IconTypeEnum.UNICODE)

  const labelPosition = ref('menu')
  const rules = reactive<FormRules>({
    cnName: [
      { required: true, message: '请输入中文名称', trigger: 'blur' },
      { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
	enName: [
	  { required: true, message: '请输入英文名称', trigger: 'blur' },
	  { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
	],
	code: [
	  { required: true, message: '请输入标识', trigger: 'blur' },
	  { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
	],
    path: [{ required: true, message: '请输入路由地址', trigger: 'blur' }],
	component: [{ required: true, message: '请输入组件', trigger: 'blur' }],
  })

  const tableData = ref<AppRouteRecord[]>([])

  onMounted(() => {
    getTableData()
  })

  const getTableData = async () => {
    loading.value = true
	const data = await MenuService.getLoadAll({
		query:formFilters
	});
	tableData.value =data;
	loading.value = false
  }


	const isEdit = ref(false)
	const formRef = ref<FormInstance>()
	const dialogTitle = ref<string>()

  const handleChange = () => {}
  const submitForm = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
      if (valid) {
        try {
			loading.value = true
			const data = await MenuService.save(form);
			form.id=data.id;
			loading.value = false
			ElMessage.success(`成功`)
			getTableData();
			dialogVisible.value = false
        } catch {
			ElMessage.error(`失败`)
        }
      }
    })
  }
  
  const openDialog = (oprType:string,type: string, parentId: string, row?: any, lock: boolean = false) => {
	  
		dialogVisible.value = true
		labelPosition.value = type
		isEdit.value = 'add'==oprType?false:true;
		lockMenuType.value = lock
		
		dialogTitle.value='add'==oprType?'新增':'编辑'
	  
		form.type=type;
	    form.id=row?.id || '';
	    form.parentId=row?.parentId||parentId;
	    form.cnName = row?.cnName || ''
	    form.enName = row?.enName || ''
	    form.code = row?.code || ''
	    form.sort = row?.sort || 1
	    
	  // 回显数据
	  if (type == 'folder') {
		dialogTitle.value+="目录";
	    // 菜单数据回显
	    form.path = row?.path || ''
	    form.component = row?.component || ''
	    form.icon = row?.icon || ''
	    form.keepAlive = row?.keepAlive || ''
	    form.show = row?.show || 0
	    form.enabled = row?.enabled || 0
	  }
	  else if (type == 'menu') {
		dialogTitle.value+="菜单";
	    // 菜单数据回显
	    form.path = row?.path || ''
	    form.component = row?.component || ''
	    form.icon = row?.icon || ''
	    form.keepAlive = row?.keepAlive
	    form.show = row?.show || 0
	    form.enabled = row?.enabled || 0
	    form.link = row?.link || ''
	    form.isIframe = row?.isIframe || 1
		form.fixed = row?.fixed || 1
	  }else{
		  dialogTitle.value+="权限";
	  }
  }

	const resetForm = () => {
		formRef.value?.resetFields()
		Object.assign(form, {
			id:'',
			parentId:'',
			cnName: '',
			enName: '',
			code:'',
			component:'',
			type:'',
			path: '',
			icon: '',
			enabled: 0,
			sort: 1,
			keepAlive: 0,
			show: 0,
			link: '',
			isIframe: 1,
			fixed:1
		})
	}

  const deleteMenu = async () => {
    try {
      await ElMessageBox.confirm('确定要删除该菜单吗？删除后无法恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })

      ElMessage.success('删除成功')
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('删除失败')
      }
    }
  }

  const deleteAuth = async () => {
    try {
      await ElMessageBox.confirm('确定要删除该权限吗？删除后无法恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })

      ElMessage.success('删除成功')
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('删除失败')
      }
    }
  }

  // 修改计算属性，增加锁定控制参数
  const disableMenuType = computed(() => {
    if (isEdit.value && labelPosition.value === 'btn') return true
    if (isEdit.value && labelPosition.value === 'menu') return true
	if (isEdit.value && labelPosition.value === 'folder') return true
    return false
  })

  // 添加一个控制变量
  const lockMenuType = ref(false)
  const isExpanded = ref(false)
  const tableRef = ref()

  const toggleExpand = () => {
    isExpanded.value = !isExpanded.value
    nextTick(() => {
      if (tableRef.value) {
        tableRef.value[isExpanded.value ? 'expandAll' : 'collapseAll']()
      }
    })
  }
  
  const formatMenuTitle=(menu:any)=>{
	  if(menu){
		  return locale.value=='zh'?menu.cnName:menu.enName;
	  }
	  return '';
  }
</script>

<style lang="scss" scoped>
  .menu-page {
    .svg-icon {
      width: 1.8em;
      height: 1.8em;
      overflow: hidden;
      vertical-align: -8px;
      fill: currentcolor;
    }

    :deep(.small-btn) {
      height: 30px !important;
      padding: 0 10px !important;
      font-size: 12px !important;
    }
  }
</style>
